package views {
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import views.components.CalendarNote;
	import views.components.CalendarSection;
	import assets.CalendarTemplate;

	/**
	 * @author Alexander Slavshik
	 * created 4.3.2011
	 */
	public class CalendarView extends Sprite {

		private var _deadline:Date
		
		private var sections:/*CalendarSection*/Array = [];
		
		private var _timer:Timer;
		
		private var days:Number;
		private var hours:Number;
		private var minutes:Number;
		private var seconds:Number;
		
		private var tmp_days:Number;
		private var tmp_hours:Number;
		private var tmp_minutes:Number;
		
		public function CalendarView() {
			
			sections[1] = new CalendarSection(Calendar.instance.Sections.Section1);
			sections[2] = new CalendarSection(Calendar.instance.Sections.Section2);
			sections[3] = new CalendarSection(Calendar.instance.Sections.Section3);
			
			_timer = new Timer(1000);
			_timer.addEventListener(TimerEvent.TIMER, onTimerTick);
		}
		
		public function start(deadline:Date):void
		{
			_deadline = deadline;
			
			onTimerTick();
			
			_timer.start();
		}
		
		private function calculate(elapsedTime:Number):void
		{
			tmp_days = days;
			tmp_hours = hours;
			tmp_minutes = minutes;
			
			days = Math.floor(elapsedTime / (1000 * 60 * 60 * 24));
			hours = Math.floor(elapsedTime / (1000 * 60 * 60));
			minutes = Math.floor(Math.floor(elapsedTime / (1000 * 60)));
			seconds = Math.floor(Math.floor(elapsedTime / 1000));
			
			seconds -= minutes * 60;
			minutes -= hours * 60;
			hours -= days * 24;
			
			if (days < 1)
			{
				
				if (tmp_hours != hours ) sections[1].addNote(hours , "h");
				if (tmp_minutes != minutes ) sections[2].addNote(minutes , "m");
				sections[3].addNote(seconds , "s");
			}
			else
			{
				if (tmp_days != days ) sections[1].addNote(days , "d");
				if (tmp_hours != hours ) sections[2].addNote(hours , "h");
				if (tmp_minutes != minutes ) sections[3].addNote(minutes , "m");
			}
		}
		
		private function onTimerTick(e:TimerEvent = null):void 
		{
			calculate(_deadline.time - new Date().time);
		}
	}
}
